from typing import Dict, Type
import logging
from core.translation_interface import TranslationEngine
from core.adapters.whisper_marian_adapter import WhisperMarianAdapter
from core.adapters.seamless_m4t_adapter import SeamlessM4TAdapter
from core.adapters.triton_adapter import TritonAdapter

logger = logging.getLogger(__name__)

class TranslationEngineFactory:
    """
    翻译引擎工厂类
    用于创建和管理不同的翻译引擎适配器
    """
    
    # 可用的引擎类型
    ENGINES = {
        "whisper_marian": WhisperMarianAdapter,      # 分步处理：Whisper + MarianMT
        "seamless_m4t": SeamlessM4TAdapter,         # 端到端：SeamlessM4T
        "triton": TritonAdapter                      # 规范要求：Triton Inference Server
    }
    
    @classmethod
    def create_engine(cls, engine_type: str, **kwargs) -> TranslationEngine:
        """
        创建指定类型的翻译引擎
        
        Args:
            engine_type: 引擎类型 ("whisper_marian", "seamless_m4t", "triton")
            **kwargs: 引擎特定的配置参数
            
        Returns:
            TranslationEngine: 翻译引擎实例
        """
        if engine_type not in cls.ENGINES:
            available = ", ".join(cls.ENGINES.keys())
            raise ValueError(f"不支持的引擎类型: {engine_type}. 可用类型: {available}")
        
        try:
            engine_class = cls.ENGINES[engine_type]
            logger.info(f"正在创建 {engine_type} 翻译引擎...")
            engine = engine_class(**kwargs)
            logger.info(f"{engine_type} 翻译引擎创建成功")
            return engine
            
        except Exception as e:
            logger.error(f"创建 {engine_type} 翻译引擎失败: {e}")
            raise
    
    @classmethod
    def get_available_engines(cls) -> Dict[str, str]:
        """获取可用的引擎类型和描述"""
        return {
            "whisper_marian": "分步处理：Whisper ASR + MarianMT 翻译",
            "seamless_m4t": "端到端：SeamlessM4T 音频翻译",
            "triton": "规范要求：Triton Inference Server"
        }
    
    @classmethod
    def get_engine_info(cls, engine_type: str) -> Dict:
        """获取指定引擎的详细信息"""
        if engine_type not in cls.ENGINES:
            return {}
        
        engine_class = cls.ENGINES[engine_type]
        
        # 基础信息
        info = {
            "type": engine_type,
            "class": engine_class.__name__,
            "module": engine_class.__module__,
            "description": cls.get_available_engines().get(engine_type, "")
        }
        
        # 尝试获取引擎特定信息
        try:
            # 创建临时实例获取信息
            temp_engine = engine_class()
            if hasattr(temp_engine, 'get_supported_languages'):
                info["supported_languages"] = temp_engine.get_supported_languages()
            
            # 清理临时实例
            if hasattr(temp_engine, 'client') and temp_engine.client:
                temp_engine.client.close()
                
        except Exception as e:
            logger.warning(f"获取 {engine_type} 引擎信息失败: {e}")
            info["error"] = str(e)
        
        return info
    
    @classmethod
    def validate_engine_config(cls, engine_type: str, config: Dict) -> bool:
        """验证引擎配置是否有效"""
        if engine_type not in cls.ENGINES:
            return False
        
        # 这里可以添加配置验证逻辑
        # 例如检查必需的参数、参数类型等
        
        if engine_type == "triton":
            required_keys = ["server_url", "model_name"]
            return all(key in config for key in required_keys)
        
        elif engine_type == "seamless_m4t":
            # SeamlessM4T 通常不需要额外配置
            return True
        
        elif engine_type == "whisper_marian":
            # WhisperMarian 通常不需要额外配置
            return True
        
        return True




